import { ref, computed, watch, nextTick } from 'vue'
import { formatSql, beautifySql } from '../utils/sqlFormatter'
import { validateSql, getSqlType, isReadOnlyQuery } from '../utils/sqlValidator'

/**
 * SQL编辑器核心功能
 * @param {Object} options - 配置选项
 * @returns {Object} 编辑器相关的响应式数据和方法
 */
export default function useSqlEditor(options = {}) {
  const {
    initialValue = '',
    autoValidate = true,
    autoFormat = false,
    debounceTime = 300,
    maxLength = 50000,
    databaseType = ''
  } = options

  // 响应式状态
  const content = ref(initialValue)
  const cursorPosition = ref(0)
  const selectionStart = ref(0)
  const selectionEnd = ref(0)
  const isReadonly = ref(false)
  const isFocused = ref(false)
  const isDirty = ref(false)
  
  // 验证相关
  const validationResult = ref({
    isValid: true,
    errors: [],
    warnings: []
  })

  // 计算属性
  const sqlType = computed(() => getSqlType(content.value))
  const isQuery = computed(() => isReadOnlyQuery(content.value))
  const characterCount = computed(() => content.value.length)
  const lineCount = computed(() => content.value.split('\n').length)
  const hasErrors = computed(() => validationResult.value.errors.length > 0)
  const hasWarnings = computed(() => validationResult.value.warnings.length > 0)
  
  // 防抖定时器
  let debounceTimer = null

  // 监听内容变化
  watch(content, (newValue, oldValue) => {
    if (newValue !== oldValue) {
      isDirty.value = true
      
      if (autoValidate) {
        debouncedValidate()
      }
    }
  })

  // 防抖验证
  const debouncedValidate = () => {
    if (debounceTimer) {
      clearTimeout(debounceTimer)
    }
    
    debounceTimer = setTimeout(() => {
      validate()
    }, debounceTime)
  }

  // 验证SQL
  const validate = () => {
    validationResult.value = validateSql(content.value, databaseType)
    return validationResult.value
  }

  // 格式化SQL
  const format = (useAdvanced = true) => {
    try {
      const formatted = useAdvanced 
        ? formatSql(content.value, databaseType)
        : beautifySql(content.value, databaseType)
      
      if (formatted && formatted !== content.value) {
        content.value = formatted
        return true
      }
    } catch (error) {
      console.warn('格式化失败:', error)
    }
    return false
  }

  // 插入文本
  const insertText = (text, position = cursorPosition.value) => {
    const before = content.value.substring(0, position)
    const after = content.value.substring(position)
    content.value = before + text + after
    
    // 更新光标位置
    nextTick(() => {
      cursorPosition.value = position + text.length
    })
  }

  // 替换选中文本
  const replaceSelection = (text) => {
    const start = Math.min(selectionStart.value, selectionEnd.value)
    const end = Math.max(selectionStart.value, selectionEnd.value)
    
    const before = content.value.substring(0, start)
    const after = content.value.substring(end)
    content.value = before + text + after
    
    // 更新光标位置
    nextTick(() => {
      cursorPosition.value = start + text.length
    })
  }

  // 获取选中文本
  const getSelectedText = () => {
    const start = Math.min(selectionStart.value, selectionEnd.value)
    const end = Math.max(selectionStart.value, selectionEnd.value)
    return content.value.substring(start, end)
  }

  // 获取当前行
  const getCurrentLine = () => {
    const lines = content.value.substring(0, cursorPosition.value).split('\n')
    return {
      number: lines.length,
      text: lines[lines.length - 1],
      start: cursorPosition.value - lines[lines.length - 1].length
    }
  }

  // 获取要执行的SQL（如果有选中则返回选中内容，否则返回全部内容）
  const getExecutableSql = () => {
    const selected = getSelectedText()
    return selected && selected.trim() ? selected : content.value
  }

  // 清空内容
  const clear = () => {
    content.value = ''
    cursorPosition.value = 0
    selectionStart.value = 0
    selectionEnd.value = 0
    isDirty.value = false
    validationResult.value = {
      isValid: true,
      errors: [],
      warnings: []
    }
  }

  // 撤销/重做功能
  const history = ref([])
  const historyIndex = ref(-1)
  const maxHistorySize = 50

  const saveToHistory = () => {
    // 移除当前位置之后的历史记录
    history.value = history.value.slice(0, historyIndex.value + 1)
    
    // 添加新的历史记录
    history.value.push({
      content: content.value,
      cursorPosition: cursorPosition.value,
      timestamp: Date.now()
    })
    
    // 限制历史记录大小
    if (history.value.length > maxHistorySize) {
      history.value = history.value.slice(-maxHistorySize)
    }
    
    historyIndex.value = history.value.length - 1
  }

  const undo = () => {
    if (historyIndex.value > 0) {
      historyIndex.value--
      const historyItem = history.value[historyIndex.value]
      content.value = historyItem.content
      cursorPosition.value = historyItem.cursorPosition
    }
  }

  const redo = () => {
    if (historyIndex.value < history.value.length - 1) {
      historyIndex.value++
      const historyItem = history.value[historyIndex.value]
      content.value = historyItem.content
      cursorPosition.value = historyItem.cursorPosition
    }
  }

  const canUndo = computed(() => historyIndex.value > 0)
  const canRedo = computed(() => historyIndex.value < history.value.length - 1)

  // 初始化历史记录
  if (initialValue) {
    saveToHistory()
  }

  // 清理函数
  const cleanup = () => {
    if (debounceTimer) {
      clearTimeout(debounceTimer)
    }
  }

  return {
    // 状态
    content,
    cursorPosition,
    selectionStart,
    selectionEnd,
    isReadonly,
    isFocused,
    isDirty,
    validationResult,
    
    // 计算属性
    sqlType,
    isQuery,
    characterCount,
    lineCount,
    hasErrors,
    hasWarnings,
    canUndo,
    canRedo,
    
    // 方法
    validate,
    format,
    insertText,
    replaceSelection,
    getSelectedText,
    getCurrentLine,
    getExecutableSql,
    clear,
    saveToHistory,
    undo,
    redo,
    cleanup
  }
} 